package main

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

func setUserIdentity(username, password string) ([]byte, error) {
	// 替换为你的认证信息
	//username := "sysadmin"
	//password := "N48XSRmcsP5YMcPf"
	tenantName := "system"
	IP := "192.168.112.133"
	source := "api"
	// 构造认证请求体
	authBody := map[string]interface{}{
		"auth": map[string]interface{}{
			"context": map[string]interface{}{
				"ip":     IP,
				"source": source,
			},
			"passwordCredentials": map[string]interface{}{
				"username": username,
				"password": password,
			},
			"tenantName": tenantName,
		},
	}
	// 转换为 JSON
	return json.Marshal(authBody)
}

func extractToken(body []byte) (string, error) {
	var raw map[string]interface{}
	if err := json.Unmarshal(body, &raw); err != nil {
		log.Printf("解析失败: %v\n", err)
		return "", nil
	}

	// 逐层提取并类型断言
	access, _ := raw["access"].(map[string]interface{})
	token, _ := access["token"].(map[string]interface{})
	id, _ := token["id"].(string)

	return fmt.Sprintf("%s", id), nil
}

func TokenPort(username, password string) (string, error) {
	url := "https://api.saltyun.com:30500/v2.0/tokens"
	method := "POST"

	//	payload := strings.NewReader(`{
	//    "auth": {
	//        "context": {
	//            "ip": "192.168.112.133",
	//            "source": "api"
	//        },
	//        "passwordCredentials": {
	//            "password": "admin@123",
	//            "username": "admin"
	//        },
	//        "tenantName": "system",
	//    }
	//}`)

	ret, err := setUserIdentity(username, password)
	if err != nil {
		log.Println("setUserIdentity err:", err)
		return "", err
	}
	payload := bytes.NewBuffer(ret)

	// ✅ 创建跳过 TLS 验证的 http.Client
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	client := &http.Client{Transport: tr}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		log.Println("http.NewRequest err:", err)
		return "", err
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		log.Println("client.Do err", err)
		return "", err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Println("io.ReadAll err:", err)
		return "", err
	}
	return extractToken(body)
}

func main() {
	token, _ := TokenPort("admin", "admin@123")
	fmt.Println("token:\n", token)
}
